package com.member.mp.web.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.member.common.cache.CacheService;
import com.member.common.core.domain.R;
import com.member.common.core.page.PageResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.enums.VerifyStatusEnum;
import com.member.common.exception.ServiceException;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.mp.config.SmsManager;
import com.member.mp.config.WxMaConfiguration;
import com.member.mp.config.WxMaProperties;
import com.member.shop.domain.*;
import com.member.shop.dto.AuthenticationDto;
import com.member.shop.dto.DevelopBuyDto;
import com.member.shop.dto.DevelopUserP2Dto;
import com.member.shop.dto.RegisterMemberDto;
import com.member.shop.service.*;
import com.member.shop.vo.*;
import io.swagger.annotations.Api;
import me.chanjar.weixin.common.error.WxErrorException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 【会员】控制器
 *
 * @author wangxin
 * @version 1.0
 * @date Mon Jul 03 22:06:51 CST 2024
 **/
@RestController
@Api(value = "会员接口", tags = {"会员接口"})
@RequestMapping("/wx/member")
public class MemberController extends SupperController {

    @Resource
    private ISysBizUserService sysBizUserService;
    @Resource
    private CacheService cacheService;
    @Resource
    private SmsManager smsManager;
    @Resource
    private ISysBizWithdrawApplyService sysBizWithdrawApplyService;
    @Resource
    private ISysBizDevelopOrderService sysBizDevelopOrderService;
    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private ISysBizMemberGradeService sysBizMemberGradeService;
    @Resource
    private ISysBizAgreementService sysBizAgreementService;
    @Value("${idCard.appCode}")
    private String appCode;

    @Value("${idCard.url}")
    private String url;


    /**
     * 注册用户(废弃)
     *
     * @param registerMemberDto 注册用户
     * @return 注册结果
     */
    @PostMapping("/registerMember")
    public R<String> registerMember(@RequestBody @Validated RegisterMemberDto registerMemberDto) throws IOException {
        // 先去查一下看是否是会员了

        try {
            Long userId = getUserId();
            SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
            if (sysBizUser != null) {
                return R.fail("您已注册会员，请勿重复注册");
            }

            sysBizUser = sysBizUserService.registerUser(registerMemberDto);
            return R.ok();
        } catch (ServiceException e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        for (String key : params.keySet()) {
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 查询我的会员 p2新加字段 fyStatus
     *
     * @return
     */
    @GetMapping("/queryMemberByUser")
    public R<UserMemberVo> queryMemberByUser() {
        Long userId = getUserId();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        UserMemberVo userMemberVo = new UserMemberVo();
        BeanUtils.copyProperties(sysBizUser, userMemberVo);
        long count = sysBizUserService.count(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getParentId, sysBizUser.getId()).eq(SysBizUser::getVerifyStatus, 1).eq(SysBizUser::getProcessStatus, 2).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
        userMemberVo.setDevelopedMembers(count);
        if (sysBizUser.getMemberGradeId() != null) {
            userMemberVo.setMemberId(sysBizUser.getMemberGradeId());
            SysBizMemberGrade sysBizMemberGrade = sysBizMemberGradeService.selectSysBizMemberGradeById(sysBizUser.getMemberGradeId());
            if (sysBizMemberGrade != null) {
                userMemberVo.setMemberId(sysBizMemberGrade.getId());
                userMemberVo.setMemberName(sysBizMemberGrade.getGradeName());
                userMemberVo.setCover(sysBizMemberGrade.getGradeIcon());
            }
        }
        if (sysBizUser.getAuthenticationStatus() == 0) {
            userMemberVo.setFyStatus(0);
        } else if (sysBizUser.getAuthenticationStatus() == 1 && sysBizUser.getFyAccountStatus() == null) {
            userMemberVo.setFyStatus(10);
        } else if (sysBizUser.getAuthenticationStatus() == 1 && sysBizUser.getFyAccountStatus() == 0) {
            userMemberVo.setFyStatus(30);
        } else if (sysBizUser.getAuthenticationStatus() == 1 && sysBizUser.getFyAccountStatus() == 1) {
            userMemberVo.setFyStatus(20);
        }
        return R.ok(userMemberVo);
    }

    @Value("${spring.profiles.active}")
    private String active;

    /**
     * P2新增 认证提交
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/toAuthentication")
    public R<String> toAuthentication(@RequestBody @Validated AuthenticationDto authenticationDto) throws IOException, JAXBException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
        if (!validate(authenticationDto.getBankNumber())) {
            return R.fail("银行卡号格式不正确");
        }
        // 实名验证start
        Map<String, String> params = new HashMap<>();
        params.put("idcard", authenticationDto.getIdCard());
        params.put("name", authenticationDto.getName());
        String result = postForm(appCode, url, params);
        JSONObject resultData = JSON.parseObject(result);
        if (!"0".equals(resultData.get("code"))) {
            return R.fail(resultData.get("message").toString());
        }
        JSONObject jsonObject = JSON.parseObject(resultData.get("result").toString());
        if ("2".equals(jsonObject.get("res").toString())) {
            return R.fail("姓名与身份证号不一致");
        }
        if (!"1".equals(jsonObject.get("res").toString())) {
            return R.fail(jsonObject.get("description").toString());
        }
        List<SysBizUser> list = sysBizUserService.list(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getIdCard, authenticationDto.getIdCard()).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
        if (!CollectionUtils.isEmpty(list) && !Objects.equals(list.get(0).getId(), getUserId())) {
            return R.fail("当前身份证号已注册");
        }
        // 实名验证end
        SysBizUser sysBizUser = sysBizUserService.getById(getUserId());
        sysBizUser.setIdCard(authenticationDto.getIdCard());
        sysBizUser.setFullName(authenticationDto.getName());
        sysBizUser.setOutAcntNo(authenticationDto.getBankNumber());
//        sysBizUser.setFyAccountStatus(0);
        sysBizUser.setAuthenticationStatus(1);
        sysBizUserService.updateById(sysBizUser);
//        // 去富友开户
//        if ("prod".equals(active)) {
//            fyPayService.createUser(sysBizUser);
//        }
        return R.ok();
    }

    public boolean validate(String bankNumber) {
        // 定义银行卡号的正则表达式
        String regex = "^[0-9]{12,19}$";

        // 创建Pattern对象
        Pattern pattern = Pattern.compile(regex);

        // 使用Pattern对象匹配银行卡号
        return pattern.matcher(bankNumber).matches();
    }

    /**
     * 查询会员等级详情
     *
     * @param id 会员等级id
     * @return
     */
    @GetMapping("/queryMemberById/{id}")
    public R<SysBizMemberGrade> queryMemberById(@PathVariable Long id) {
        SysBizMemberGrade sysBizMemberGrade = sysBizMemberGradeService.selectSysBizMemberGradeById(id);
        return R.ok(sysBizMemberGrade);
    }

    /**
     * 查询我的会员详情
     *
     * @return
     */
    @GetMapping("/queryRegisterMember")
    public R<UserRegistMemberVo> queryRegisterMember() {
        Long userId = getUserId();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        UserRegistMemberVo userMemberVo = new UserRegistMemberVo();
        BeanUtils.copyProperties(sysBizUser, userMemberVo);
        Long parentId = sysBizUser.getParentId();
        userMemberVo.setInvitationCode(StringUtils.EMPTY);
        if (sysBizUser.getParentUserId() != null) {
            SysBizUser parentUser = sysBizUserService.selectSysBizUserById(sysBizUser.getParentUserId());
            if (parentUser != null) {
                userMemberVo.setInvitationCode(parentUser.getInvitationCode());
            }
        }
        if (parentId != null) {
            SysBizUser parentUser = sysBizUserService.selectSysBizUserById(parentId);
            if (parentUser != null) {
                userMemberVo.setInvitationCode(parentUser.getInvitationCode());
            }
        }
        return R.ok(userMemberVo);
    }

    /**
     * 查询银行卡账户信息
     *
     * @return
     */
    @GetMapping("/queryBank")
    public R<BankVo> queryBank() {
        Long userId = getUserId();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        BankVo bankVo = new BankVo();
        BeanUtils.copyProperties(sysBizUser, bankVo);
        return R.ok(bankVo);
    }

    /**
     * 新增或修改银行卡账户信息
     *
     * @return
     */
    @PostMapping("/saveOrUpdateBank")
    public R<String> saveOrUpdateBank(@RequestBody @Validated BankVo bankDto) {
        // 先判断验证码
        if (!cacheService.exists(bankDto.getBankPhone()) || !bankDto.getCode().equals(cacheService.get(bankDto.getBankPhone()) + "")) {
            return R.fail("验证码错误");
        }
        Long userId = getUserId();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        sysBizUser.setBankPhone(bankDto.getBankPhone());
        sysBizUser.setBankUserName(bankDto.getBankUserName());
        sysBizUser.setBankBranch(bankDto.getBankBranch());
        sysBizUser.setBankName(bankDto.getBankName());
        sysBizUser.setBankCardNumber(bankDto.getBankCardNumber());
        // 去富友绑卡
//        if ("prod".equals(active) && !sysBizUser.getOutAcntNo().equals(sysBizUser.getBankCardNumber())) {
//            String message = fyPayService.modifyAccountInCard(sysBizUser);
//            if (StringUtils.isNotBlank(message)) {
//                return R.fail(message);
//            }
//        }
        sysBizUserService.updateById(sysBizUser);
        return R.ok();
    }

    /**
     * 发送验证码
     *
     * @return
     */
    @PostMapping("/verificationCode/{phoneNum}")
    public R<String> verificationCode(@PathVariable("phoneNum") String phoneNum) throws Exception {
        String code = String.format("%6d", 100000 + new Random().nextInt(900000));
        if (cacheService.exists(phoneNum)) {
            cacheService.remove(phoneNum);
        }
        if (cacheService.setNX(phoneNum, code, 60 * 5)) {
            smsManager.sendCode(code, phoneNum);
        }
        return R.ok();
    }

    /**
     * 提现
     *
     * @param amount 提现金额
     * @return
     */
    @PostMapping("/withdrawal/{amount}")
    public R<String> withdrawal(@PathVariable BigDecimal amount) {
        Long userId = getUserId();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        if (sysBizUser.getUnwithdrawnBalance().compareTo(amount) < 0) {
            return R.fail("余额不足");
        }
        sysBizUserService.withdrawal(sysBizUser, amount);
        return R.ok();
    }

    /**
     * 查询提现记录（带分页）
     *
     * @return
     */
    @GetMapping("/queryWithdrawal")
    public R<PageResult<WithdrawalLogVo>> queryWithdrawal() {
        startPage();
        LambdaQueryWrapper<SysBizWithdrawApply> sysBizWithdrawApplyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizWithdrawApplyLambdaQueryWrapper.eq(SysBizWithdrawApply::getUserId, getUserId());
        sysBizWithdrawApplyLambdaQueryWrapper.orderByDesc(SysBizWithdrawApply::getId);
        List<SysBizWithdrawApply> sysBizWithdrawApplies = sysBizWithdrawApplyService.selectSysBizWithdrawApplyList(sysBizWithdrawApplyLambdaQueryWrapper);
        TableDataInfo dataTable = getDataTable(sysBizWithdrawApplies);
        List<?> rows = dataTable.getRows();
        ArrayList<WithdrawalLogVo> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizWithdrawApply sysBizWithdrawApply = (SysBizWithdrawApply) row;
            WithdrawalLogVo target = new WithdrawalLogVo();
            BeanUtils.copyProperties(sysBizWithdrawApply, target);
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }

    /**
     * 查询购买发展会员简介
     *
     * @return
     */
    @GetMapping("/queryDevelop")
    public R<DevelopGoodsVo> queryDevelop() {
        DevelopGoodsVo developGoodsVo = sysBizWithdrawApplyService.queryDevelop();
        return R.ok(developGoodsVo);
    }

    /**
     * 组装发展会员订单信息
     *
     * @param developBuyDto 参数
     * @return
     */
    @PostMapping("/perDevelopOrder")
    public R<DevelopOrderVo> perDevelopOrder(@RequestBody DevelopBuyDto developBuyDto) {
        Long userId = getUserId();
        DevelopOrderVo developOrderVo = sysBizDevelopOrderService.perDevelopOrder(developBuyDto, userId);
        return R.ok(developOrderVo);
    }

    /**
     * 删除申请会员信息
     *
     * @return
     */
    @PostMapping("/deleteMemberInfo")
    public R<String> deleteMemberInfo() {
        Long userId = getUserId();
        sysBizUserService.updateMemberInfoByNull(userId);
        return R.ok();
    }

    @Resource
    private WxMaProperties wxMaProperties;

    /**
     * 支付发展会员
     *
     * @param developBuyDto 参数
     * @return
     */
    @PostMapping("/paymentDevelop")
    public R<SysBizDevelopOrder> paymentDevelop(@RequestBody DevelopBuyDto developBuyDto) throws WxErrorException {
        Long userId = getUserId();
        SysBizUser byId = sysBizUserService.getById(getUserId());
        if (byId.getUserRole() == 0) {
            return R.notRegister("请先注册会员");
        }
        if (StringUtils.isBlank(byId.getOpenId()) && StringUtils.isNotBlank(developBuyDto.getCode())) {
            String appid = wxMaProperties.getConfigs().get(0).getAppid();
            final WxMaService wxService = WxMaConfiguration.getMaService(appid);
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(developBuyDto.getCode());
            byId.setOpenId(session.getOpenid());
            sysBizUserService.updateById(byId);
        }
        SysBizDevelopOrder sysBizDevelopOrder = sysBizDevelopOrderService.paymentDevelop(developBuyDto, userId);
        return R.ok(sysBizDevelopOrder);
    }

    @PostMapping("/wxPay/{id}")
    public R<WxPayMpOrderResult> wxPay(@PathVariable Long id) {
        SysBizDevelopOrder sysBizDevelopOrder = sysBizDevelopOrderService.getById(id);
        if (sysBizDevelopOrder == null) {
            return R.fail("订单不存在");
        }
        if (sysBizDevelopOrder.getPaymentStatus() == 1) {
            return R.fail("订单已支付");
        }
        if (sysBizDevelopOrder.getPaymentTimeEnd().compareTo(DateUtils.getNowDate()) <= 0) {
            return R.fail("订单已过期,请重新下单");
        }
        try {
//            return R.ok(sysBizDevelopOrderService.wxPay(sysBizDevelopOrder));
            return R.ok();
        } catch (Exception e) {
            logger.error("发展会员订单支付失败 =>", e);
            return R.fail("支付失败");
        }
    }

    /**
     * 查询发展会员购买记录（带分页）
     *
     * @return
     */
    @GetMapping("/queryDevelopBuyLog")
    public R<PageResult<DevelopBuyLogVo>> queryDevelopBuyLog() {
        startPage();
        LambdaQueryWrapper<SysBizDevelopOrder> sysBizDevelopOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizDevelopOrderLambdaQueryWrapper.eq(SysBizDevelopOrder::getUserId, getUserId());
        sysBizDevelopOrderLambdaQueryWrapper.eq(SysBizDevelopOrder::getPaymentStatus, 1);
        sysBizDevelopOrderLambdaQueryWrapper.orderByDesc(SysBizDevelopOrder::getId);
        List<SysBizDevelopOrder> sysBizDevelopOrders = sysBizDevelopOrderService.selectSysBizDevelopOrderList(sysBizDevelopOrderLambdaQueryWrapper);
        TableDataInfo dataTable = getDataTable(sysBizDevelopOrders);
        List<?> rows = dataTable.getRows();
        ArrayList<DevelopBuyLogVo> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizDevelopOrder sysBizDevelopOrder = (SysBizDevelopOrder) row;
            DevelopBuyLogVo target = new DevelopBuyLogVo();
            BeanUtils.copyProperties(sysBizDevelopOrder, target);
            target.setUserName(StringUtils.isBlank(sysBizDevelopOrder.getUserName()) ? "默认昵称" : sysBizDevelopOrder.getUserName());
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }

    /**
     * 查询购买记录详情
     *
     * @param id 购买记录id
     * @return
     */
    @GetMapping("/queryDevelopDetail/{id}")
    public R<DevelopOrderVo> queryDevelopDetail(@PathVariable Long id) {
        DevelopOrderVo developOrderVo = sysBizDevelopOrderService.queryDevelopDetail(id);
        return R.ok(developOrderVo);
    }

    /**
     * 查询发展会员订单（带分页）
     *
     * @return
     */
    @GetMapping("/queryDevelopMemberOrder")
    public R<PageResult<DevelopMemberOrderVo>> queryDevelopMemberOrder() {
        List<Long> userIdList = sysBizDevelopOrderService.queryDevelopUserId(getUserId());
        if (CollectionUtils.isEmpty(userIdList)) {
            return R.ok();
        }
        startPage();
        List<SysBizOrder> sysBizOrderList = sysBizOrderService.queryDevelopMemberOrder(userIdList);
        TableDataInfo dataTable = getDataTable(sysBizOrderList);
        List<?> rows = dataTable.getRows();
        ArrayList<DevelopMemberOrderVo> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizOrder sysBizOrder = (SysBizOrder) row;
            DevelopMemberOrderVo target = new DevelopMemberOrderVo();
            BeanUtils.copyProperties(sysBizOrder, target);
            SysBizUser sysBizUser = sysBizUserService.getById(sysBizOrder.getUserId());
            if (sysBizUser != null) {
                target.setUserName(StringUtils.isBlank(sysBizUser.getFullName()) ? StringUtils.isBlank(sysBizUser.getNickName()) ? "默认昵称" : sysBizUser.getNickName() : sysBizUser.getFullName());
                target.setPhone(sysBizUser.getUserPhone());
            }
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }

    /**
     * p2修改为只查询未核实的会员，只传分页参数，不传其他的-会员团：查询发展会员列表（带分页）
     *
     * @return
     */
    @GetMapping("/queryDevelopUser")
    public R<PageResult<DevelopUserVo>> queryDevelopUser() {
        startPage();
        LambdaQueryWrapper<SysBizUser> sysBizUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizUserLambdaQueryWrapper.eq(SysBizUser::getParentId, getUserId());
        sysBizUserLambdaQueryWrapper.eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        sysBizUserLambdaQueryWrapper.ne(SysBizUser::getProcessStatus, 3);
        sysBizUserLambdaQueryWrapper.eq(SysBizUser::getVerifyStatus, 0);
        sysBizUserLambdaQueryWrapper.orderByDesc(SysBizUser::getId);
        List<SysBizUser> sysBizUsers = sysBizUserService.selectSysBizUserList(sysBizUserLambdaQueryWrapper);
        TableDataInfo dataTable = getDataTable(sysBizUsers);
        List<?> rows = dataTable.getRows();
        ArrayList<DevelopUserVo> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizUser sysBizUser = (SysBizUser) row;
            DevelopUserVo target = new DevelopUserVo();
            BeanUtils.copyProperties(sysBizUser, target);
            target.setUserName(sysBizUser.getFullName());
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }

    /**
     * p2新增，查询会员等级
     *
     * @return 会员等级列表
     */
    @GetMapping("/queryMemberList")
    public R<List<SysBizMemberGrade>> queryMemberList() {
        List<SysBizMemberGrade> sysBizMemberGrades = sysBizMemberGradeService.list(new LambdaQueryWrapper<SysBizMemberGrade>().eq(SysBizMemberGrade::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()).eq(SysBizMemberGrade::getDisplayed, EnableStatusEnum.ENABLE.getKey()));
        return R.ok(sysBizMemberGrades);
    }

    /**
     * p2新增，查询已核实我的会员团（带分页）
     *
     * @return 会员等级列表
     */
    @GetMapping("/queryDevelopUserP2")
    public R<PageResult<DevelopUserP2Vo>> queryDevelopUserP2(DevelopUserP2Dto developUserP2Dto) {
        Long userId = getUserId();
        SysBizUser sysBizUser = sysBizUserService.getById(userId);
        if (developUserP2Dto != null && developUserP2Dto.getUserId() != null) {
            userId = developUserP2Dto.getUserId();
        }
        Integer level = 30;
        if (sysBizUser.getMemberGradeId() != null) {
            SysBizMemberGrade sysBizMemberGrade = sysBizMemberGradeService.getById(sysBizUser.getMemberGradeId());
            if (sysBizMemberGrade != null && sysBizMemberGrade.getDeleted() == 0 && sysBizMemberGrade.getDisplayed() == 0) {
                level = sysBizMemberGrade.getLevel();
            }
        }
        startPage();
        List<DevelopUserP2Vo> developUserP2VoList = sysBizUserService.queryDevelopUserP2(developUserP2Dto, level, userId);
        TableDataInfo dataTable = getDataTable(developUserP2VoList);
        return R.ok(new PageResult<>(dataTable.getTotal(), developUserP2VoList));
    }

    /**
     * p2新增，核实会员
     *
     * @return 会员等级列表
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/verifyUser/{id}")
    public R<String> verifyUser(@PathVariable Long id) {
        SysBizUser sysBizUser = sysBizUserService.getById(id);
        if (sysBizUser == null || sysBizUser.getDeleted().equals(OrderDeleteEnum.DELETE.getKey())) {
            return R.fail("用户不存在");
        }
        if (sysBizUser.getVerifyStatus().equals(VerifyStatusEnum.APPROVED.getKey())) {
            return R.fail("用户已核实");
        }
        SysBizUser user = sysBizUserService.getById(getUserId());
        if (user.getAvailableMembers() < 1L) {
            return R.fail("可发展会员数量不足");
        }
        Long gradeId = null;
        if (sysBizUser.getMemberGradeId() == null) {
            List<SysBizMemberGrade> sysBizMemberGradeList = sysBizMemberGradeService.list(new LambdaQueryWrapper<SysBizMemberGrade>().eq(SysBizMemberGrade::getGradeName, "经销商").eq(SysBizMemberGrade::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
            if (!sysBizMemberGradeList.isEmpty()) {
                gradeId = sysBizMemberGradeList.get(0).getId();
            }
        }
        sysBizUserService.update(new LambdaUpdateWrapper<>(SysBizUser.class).set(SysBizUser::getVerifyStatus, VerifyStatusEnum.APPROVED.getKey()).set(SysBizUser::getVerifyTime, DateUtils.getNowDate()).set(SysBizUser::getProcessStatus, 2).set(SysBizUser::getUserRole, 1).set(gradeId != null, SysBizUser::getMemberGradeId, gradeId).set(SysBizUser::getProcessTime, DateUtils.getNowDate()).eq(SysBizUser::getId, id));
        sysBizUserService.update(new LambdaUpdateWrapper<>(SysBizUser.class).set(SysBizUser::getAvailableMembers, user.getAvailableMembers() - 1L).eq(SysBizUser::getId, getUserId()));
        return R.ok();
    }

    /**
     * 分享查询海报和邀请码
     *
     * @return
     */
    @GetMapping("/queryShare")
    public R<ShareVo> queryShare() {
        ShareVo shareVo = new ShareVo();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(getUserId());
        shareVo.setCode(sysBizUser.getInvitationCode());
        SysBizAgreement sysBizAgreement = sysBizAgreementService.selectSysBizAgreementById(1L);
        shareVo.setImage(sysBizAgreement.getPoster());
        return R.ok(shareVo);
    }
}
